
//  LoginVC.m
//  phmall
//
//  Created by admin on 2017/9/21.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "LoginVC.h"
#import "TabBarVController.h"
#import "RegisterVC.h"
#import "RetrieveViewController.h"
@interface LoginVC ()<UITextFieldDelegate>{
    UITextField *name;
    UITextField *passWord;
    UIButton    *show;
}
@property(nonatomic,strong)MBProgressHUD *hud;
@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    [self setUI];
    if ([self.type isEqualToString:@"new"]) {
        self.title=Localized(@"登录");
    }
    if ([self.type isEqualToString:@"google"]) {
        self.title=@"绑定google账号";
    }
    if ([self.type isEqualToString:@"facebook"]) {
        self.title=@"绑定facebook账号";
    }
    // Do any additional setup after loading the view.
}
-(void)rightBarAction{
    
}

-(void)setUI{
    UIBarButtonItem *rightBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"帮助中心"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarAction)];
    self.navigationItem.rightBarButtonItem=rightBar;
    
    UIBarButtonItem *leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回-1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    self.navigationItem.leftBarButtonItem=leftBar;
    
    UIImageView *logo=[[UIImageView alloc]init];
    [self.view addSubview:logo];
   
    logo.image=[UIImage imageNamed:@"logo"];
    ViewBorderRadius(logo, 10, 0, [UIColor whiteColor]);
    [logo mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset((218-RectStatus.size.height-44-64));
        make.centerX.equalTo(self.view);
        make.width.height.offset(70);
        make.height.equalTo(logo.mas_width);
    }];
    
    name=[[UITextField alloc]init];
    name.placeholder=Localized(@"用户名");
//    name.text=@"admin";
    name.autocapitalizationType = UITextAutocapitalizationTypeNone;
    name.keyboardType=UIKeyboardTypeDefault;
    name.font=[UIFont systemFontOfSize:18];
    [self.view addSubview:name];
    [name mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(30);
        make.right.equalTo(self.view.mas_right).with.offset(-60);
        make.top.equalTo(logo.mas_bottom).with.offset(20);
        make.height.offset(40);
    }];
    
    UIView *nameLine=[[UILabel alloc]init];
    [self.view addSubview:nameLine];
    nameLine.backgroundColor=[UIColor orangeColor];
    [nameLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(name.mas_bottom);
        make.right.equalTo(self.view.mas_right).with.offset(-20);
        make.left.equalTo(self.view).with.offset(20);
        make.height.offset(1);
    }];
    
    passWord=[[UITextField alloc]init];
    passWord.placeholder=Localized(@"密码");
    passWord.delegate=self;
//    passWord.text=@"admin1";
    passWord.font=[UIFont systemFontOfSize:18];
    passWord.secureTextEntry = YES;
    [self.view addSubview:passWord];
    passWord.keyboardType=UIKeyboardTypeASCIICapable;
    [passWord mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(30);
        make.right.equalTo(self.view.mas_right).with.offset(-60);
        make.top.equalTo(name.mas_bottom).with.offset(30);
        make.height.offset(40);
    }];
    
    show=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:show];
    [show setImage:[UIImage imageNamed:@"密码显示-未点击输入框"] forState:UIControlStateNormal];
    [show setImage:[UIImage imageNamed:@"隐藏密码-未点击输入框"] forState:UIControlStateSelected];
    [show addTarget:self action:@selector(showPassWord:) forControlEvents:UIControlEventTouchUpInside];
    [show mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(passWord.mas_right);
        make.centerY.equalTo(passWord);
        make.width.height.offset(24);
    }];
    
    UIView *passLine=[[UILabel alloc]init];
    [self.view addSubview:passLine];
    passLine.backgroundColor=[UIColor orangeColor];
    [passLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(passWord.mas_bottom);
        make.right.equalTo(self.view.mas_right).with.offset(-20);
        make.left.equalTo(self.view).with.offset(20);
        make.height.offset(1);
    }];

    UIButton *login=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:login];
    [login setBackgroundImage:[UIImage imageNamed:@"背景渐变条"] forState:UIControlStateNormal];
    [self.type isEqualToString:@"login"] ?  [login setTitle:Localized(@"登录") forState:UIControlStateNormal]: [login setTitle:@"绑定" forState:UIControlStateNormal];
    [login addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    [login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    login.backgroundColor=[UIColor colorWithHexString:@"#ff9300"];
//    ViewBorderRadius(login, 5, 1, [UIColor colorWithHexString:@"#ff9300"]);
    [login mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(passLine.mas_bottom).with.offset(50);
        make.height.offset(44);
        make.left.equalTo(self.view).with.offset(20);
        make.right.equalTo(self.view.mas_right).with.offset(-20);
    }];
    
    UIButton *registered=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:registered];
    [registered setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [registered setTitle:Localized(@"新用户注册") forState:UIControlStateNormal];
    registered.titleLabel.font=[UIFont systemFontOfSize:13];
    [registered addTarget:self action:@selector(gotoRegister) forControlEvents:UIControlEventTouchUpInside];
    [registered mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(login.mas_bottom).with.offset(15);
        make.left.equalTo(self.view).with.offset(20);
    }];
    
    UIButton *retrieve=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:retrieve];
    retrieve.titleLabel.font=[UIFont systemFontOfSize:13];
    [retrieve setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [retrieve setTitle:Localized(@"找回密码") forState:UIControlStateNormal];
    [retrieve addTarget:self action:@selector(gotoRetrieve) forControlEvents:UIControlEventTouchUpInside];
    [retrieve mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(login.mas_bottom).with.offset(15);
        make.right.equalTo(self.view).with.offset(-20);
    }];
}
-(void)gotoRetrieve{
    RetrieveViewController *regis=[[RetrieveViewController alloc]init];
    [self.navigationController pushViewController:regis animated:YES];
}
-(void)gotoRegister{
    RegisterVC *regis=[[RegisterVC alloc]init];
    regis.type=@"new";
    [self.navigationController pushViewController:regis animated:YES];
}
-(void)showPassWord:(UIButton *)but{
    show.selected=!show.selected;
 
    if (show.selected) {
        passWord.secureTextEntry = NO;
    }else{
        passWord.secureTextEntry = YES;
    }
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if (textField==passWord) {
        [show setImage:[UIImage imageNamed:@"密码显示-输入内容后"] forState:UIControlStateNormal];
        [show setImage:[UIImage imageNamed:@"隐藏密码-输入内容后"] forState:UIControlStateSelected];
    }
}
- (void)loginAction{
    if (name.text==0||passWord.text.length==0) {
        [PublicClass ProgressHUDModeText:@"用户名密码不可为空" andTime:2];
        return;
    }
    [self loadDataWithlogin];

}
- (void)loadDataWithlogin{
    self.hud =[MBProgressHUD showHUDAddedTo:self.view  animated:YES];
    self.hud.detailsLabel.text = Localized(@"加载中...");
    if ([self.type isEqualToString:@"login"]) {
        NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"login"];
        NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
        [parametersDic setValue:name.text forKey:@"username"];
        [parametersDic setValue:passWord.text  forKey:@"password"];
        [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
             [self.hud hideAnimated:YES];
            NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            if ([responseDict[@"ret"] isEqualToString:@"200"]) {
                if ([responseDict[@"data"][@"status"] isEqualToString:@"Success"]) {
                    [PublicClass ProgressHUDModeText:Localized(@"登录成功") andTime:2];
                    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC));
                    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//                        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:[NSNumber numberWithBool:YES]];
                        [self dismissViewControllerAnimated:YES completion:nil];
                    });
                }else if([responseDict[@"data"][@"status"] isEqualToString:@"Fail"]){
                    [PublicClass ProgressHUDModeText:Localized(@"用户名或密码错误") andTime:2];
                }else{
                    [PublicClass ProgressHUDModeText:Localized(@"该账号已登录") andTime:2];
                }
            }
            
        } andFailure:^{
            [self.hud hideAnimated:YES];
            [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2];
        }];
    }else{
        NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"login/bind"];
        NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
        if ([self.type isEqualToString:@"google"]) {
            [parametersDic setValue:name.text forKey:@"username"];
            [parametersDic setValue:passWord.text forKey:@"password"];
            [parametersDic setValue:[GIDSignIn sharedInstance].currentUser.userID forKey:@"oauth_uid"];
            [parametersDic setValue:[GIDSignIn sharedInstance].currentUser.authentication.idToken forKey:@"token"];
            [parametersDic setValue:self.type forKey:@"type"];
        }
        if ([self.type isEqualToString:@"facebook"]) {
            [parametersDic setValue:name.text forKey:@"username"];
            [parametersDic setValue:passWord.text forKey:@"password"];
            [parametersDic setValue:[FBSDKAccessToken currentAccessToken].userID forKey:@"oauth_uid"];
            [parametersDic setValue:[FBSDKAccessToken currentAccessToken].tokenString  forKey:@"token"];
            [parametersDic setValue:self.type forKey:@"type"];
        }
        [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
            NSMutableDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            [self.hud hideAnimated:YES];
            if ([responseDict[@"ret"] isEqualToString:@"200"]) {
                [PublicClass ProgressHUDModeText:Localized(@"登录成功") andTime:2];
//                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:[NSNumber numberWithBool:YES]];
                 [self dismissViewControllerAnimated:YES completion:nil];
            }else{
                [PublicClass ProgressHUDModeText:responseDict[@"err"] andTime:2];
            }
        } andFailure:^{
            [self.hud hideAnimated:YES];
           
        }];
    }
   
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
////点击登陆后的操作
//- (void)loginWithUsername:(NSString *)username password:(NSString *)password
//{
////    [self showHudInView:self.view hint:NSLocalizedString(@"login.ongoing", @"Is Login...")];
//    //异步登陆账号
//    __weak typeof(self) weakself = self;
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        EMError *error = [[EMClient sharedClient] loginWithUsername:username password:password];
//
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [weakself hideHud];
//            if (!error) {
//                //设置是否自动登录
//                [[EMClient sharedClient].options setIsAutoLogin:YES];
//
//                //保存最近一次登录用户名
//                [weakself saveLastLoginUsername];
//
//                //发送自动登陆状态通知
//                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:[NSNumber numberWithBool:YES]];
//
//            } else {
//                switch (error.code)
//                {
//                    case EMErrorUserNotFound:
//                        //                        TTAlertNoTitle(NSLocalizedString(@"error.usernotExist", @"User not exist!"));
//                        break;
//                    case EMErrorNetworkUnavailable:
//                        //                        TTAlertNoTitle(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
//                        break;
//                    case EMErrorServerNotReachable:
//                        //                        TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
//                        break;
//                    case EMErrorUserAuthenticationFailed:
//                        //                        TTAlertNoTitle(error.errorDescription);
//                        break;
//                    case EMErrorServerTimeout:
//                        //                        TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
//                        break;
//                    case EMErrorServerServingForbidden:
//                        //                        TTAlertNoTitle(NSLocalizedString(@"servingIsBanned", @"Serving is banned"));
//                        break;
//                    case EMErrorUserLoginTooManyDevices:
//                        //                        TTAlertNoTitle(NSLocalizedString(@"alert.multi.tooManyDevices", @"Login too many devices"));
//                        break;
//                    default:
//                        //                        TTAlertNoTitle(NSLocalizedString(@"login.fail", @"Login failure"));
//                        break;
//                }
//            }
//        });
//    });
//}

//-(void)doRegister:(id)sender
//{
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        EMError *error = [[EMClient sharedClient] registerWithUsername:name.text password:passWord.text];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (!error) {
//                //                TTAlertNoTitle(NSLocalizedString(@"register.success", @"Registered successfully, please log in"));
//            }else{
//                switch (error.code) {
//                    case EMErrorServerNotReachable:
//                        //                        TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
//                        break;
//                    case EMErrorUserAlreadyExist:
//                        //                        TTAlertNoTitle(NSLocalizedString(@"register.repeat", @"You registered user already exists!"));
//                        break;
//                    case EMErrorNetworkUnavailable:
//                        //                        TTAlertNoTitle(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
//                        break;
//                    case EMErrorServerTimeout:
//                        //                        TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
//                        break;
//                    case EMErrorServerServingForbidden:
//                        //                        TTAlertNoTitle(NSLocalizedString(@"servingIsBanned", @"Serving is banned"));
//                        break;
//                    default:
//                        //                        TTAlertNoTitle(NSLocalizedString(@"register.fail", @"Registration failed"));
//                        break;
//                }
//            }
//        });
//    });
//}
//#pragma  mark - private
//
//- (void)saveLastLoginUsername
//{
////    NSString *username = [[EMClient sharedClient] currentUsername];
//    if (username && username.length > 0) {
//        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
//        [ud setObject:username forKey:[NSString stringWithFormat:@"em_lastLogin_username"]];
//        [ud synchronize];
//    }
//}

//- (NSString*)lastLoginUsername
//{
//    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
//    NSString *username = [ud objectForKey:[NSString stringWithFormat:@"em_lastLogin_username"]];
//    if (username && username.length > 0) {
//        return username;
//    }
//    return nil;
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
